package com.ruoyi.auth.service;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.ruoyi.common.core.utils.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/*
阿里云短信业务
* */
@Service
public class MSMService {
    @Value("${aliyun.sms.regionId}")
    String REGION_Id;

    @Value("${aliyun.sms.accessKeyId}")
    private String ACCESS_KEY_ID;

    @Value("${aliyun.sms.secret}")
    private String SECRECT;

    @Value("${aliyun.sms.TemplateCode}")
    private String TemplateCode;

    @Value("${aliyun.sms.SignName}")
    private String SignName;

    public boolean send(String phone, String code) {
        //判断手机号是否为空
        if (StringUtils.isEmpty(phone)) {
            return false;
        }
        //整合阿里云短信服务
        //设置相关参数
        DefaultProfile profile = DefaultProfile.
                getProfile(REGION_Id,
                        ACCESS_KEY_ID,
                        SECRECT);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);//提交方式
        request.setDomain("dysmsapi.aliyuncs.com");//域名
        request.setVersion("2017-05-25");//版本
        request.setAction("SendSms");

        //手机号
        request.putQueryParameter("PhoneNumbers", phone);
        //签名名称
        request.putQueryParameter("SignName", SignName);
        //模板code
        request.putQueryParameter("TemplateCode", TemplateCode);
        //验证码  使用json格式   {"code":"123456"}
        Map<String, Object> param = new HashMap();
        param.put("code", code);
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));

        //调用方法进行短信发送
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            System.out.println(response.getHttpResponse().isSuccess());
            return response.getHttpResponse().isSuccess();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }
}



